package com.mybatis.dao;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.ibatis.type.TypeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.mybatis.dao.annotation.TypeScan;
import com.mybatis.dao.config.FactoryConfig;
import com.mybatis.dao.typehandler.ArrayIntToStringTypeHandler;
import com.mybatis.dao.typehandler.ArrayLongToStringTypeHandler;
import com.mybatis.dao.typehandler.ArrayToStringTypeHandler;
import com.mybatis.dao.typehandler.GenericEnumTypeHandler;
import com.mybatis.dao.typehandler.ListStringTypeHandler;

public class SessionFactoryConfig {
	
	@Autowired
	private FactoryConfig factoryConfig;

	public DataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setDriverClassName(factoryConfig.getJdbcDriverClass());
		datasource.setUrl(factoryConfig.getJdbcUrl());
		datasource.setUsername(factoryConfig.getJdbcUsername());
		datasource.setPassword(factoryConfig.getJdbcPassword());
		return datasource;
	}

	public DataSourceTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource());
	}

	@SuppressWarnings("rawtypes")
	public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(factoryConfig.getMybatisConfigXml()));
		PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + factoryConfig.getMapperXml();
		sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
		sqlSessionFactoryBean.setDataSource(dataSource());
		sqlSessionFactoryBean.setTypeAliasesPackage(factoryConfig.getTypeAliasPackage());		
		
		sqlSessionFactoryBean.setTypeHandlersPackage(factoryConfig.getTypeHandlersPackage());
		TypeHandler[] typeHandlers= {new GenericEnumTypeHandler<DescriptionID>(),
		        new ArrayIntToStringTypeHandler(),new ArrayLongToStringTypeHandler(),
		        new ArrayToStringTypeHandler(),new ListStringTypeHandler()};
		sqlSessionFactoryBean.setTypeHandlers(typeHandlers);
		
		Map<String, String> scanMap = new HashMap<String, String>();
		scanMap.put(TypeScan.enumToInt.name(), factoryConfig.getScanEnumPackage());
		sqlSessionFactoryBean.setTypeScanMap(scanMap);
		return sqlSessionFactoryBean;
	}

}
